﻿#include "userlist.h"
#include "ui_userlist.h"
#include "msgapi.h"
#include "userregister.h"
#include <QMessageBox>
#include <QList>

UserList::UserList(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserList) {
    ui->setupUi(this);
    initList();
    initWidget();
}

UserList::~UserList() {
    delete ui;
}

int UserList::getCurrentPage() {
    return currentPage;
}

int UserList::getTotalRecord() {
    return totalRecord;
}

void UserList::setTotalRecord(int totalRecord) {
    this->totalRecord = totalRecord;
}

int UserList::getTotalPage() {
    return totalPage;
}

void UserList::setTotalPage(int totalPage) {
    this->totalPage = totalPage;
}

QString UserList::getCurrentSearchUsername() {
    return ui->searchUsernameLineEdit->text();
}

QString UserList::getCurrentSearchStartTime() {
    return ui->startTimeEdit->text();
}

QString UserList::getCurrentSearchEndTime() {
    return ui->endTimeEdit->text();
}

void UserList::setCurrentEndDateTime() {
    ui->endTimeEdit->setDateTime(QDateTime::currentDateTime());
}

void UserList::initList() {
    QStringList headerText;
    headerText << QString("ID")
               << QString("用户名")
               << QString("注册图片")
               << QString("ID卡号")
               << QString("注册时间");
    // 指定列数
    ui->tableWidget->setColumnCount(5);
    // 设置颜色交替显示
    ui->tableWidget->setAlternatingRowColors(true);
    // 自适应宽度
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    //设置行高
    ui->tableWidget->verticalHeader()->setDefaultSectionSize(60);
    // 设置行宽
//    ui->tableWidget->horizontalHeader()->setDefaultSectionSize(100);
    // 设置垂直头不可见
    ui->tableWidget->verticalHeader()->setVisible(false);
    // 设置表头的高度
    ui->tableWidget->horizontalHeader()->setFixedHeight(45);

    // 为表格控件添加表头
    for(int i = 0; i < ui->tableWidget->columnCount(); i++) {
        // 给每个单元格添加一个 QTableWidgetItem实例
        QTableWidgetItem *item = new  QTableWidgetItem;
        // 设置文本
        item->setText(headerText.at(i));
        // 设置表头的字体
        QFont font;
        font.setBold(true);//加粗
        item->setFont(font);

        // 将单元格设置到 表格控件上 ，并且作为 表头
        ui->tableWidget->setHorizontalHeaderItem(i, item);
    }

    // 表格适应列
//    ui->tableWidget->setColumnWidth(1, 200);
//    ui->tableWidget->setColumnWidth(2, 100);

}

void UserList::initWidget() {
    ui->pageLabel->setAlignment(Qt::AlignVCenter);
    setCurrentEndDateTime();
    currentPage = 1;
    totalRecord = 0;
    getUserList(currentPage, USER_PAGE_LIST_SIZE,
                getCurrentSearchUsername(), getCurrentSearchStartTime(), getCurrentSearchEndTime());
}

void UserList::getUserList(int page, int pageSize, QString currentSearchUsername,
                           QString currentSearchStartTime, QString currentSearchEndTime) {
    MsgApi::getMsgApi()->getUserInfoList(page, pageSize,
                                         currentSearchUsername, currentSearchStartTime, currentSearchEndTime);
}

void UserList::setPageShow(int count) {
    // 设置页面情况
    int totalPage = 0;
    if(count == USER_PAGE_LIST_SIZE) {
        totalPage = 1;
    } else {
        totalPage = count / USER_PAGE_LIST_SIZE + 1;
    }
    setTotalRecord(count);
    setTotalPage(totalPage);
    ui->pageLabel->setText(QString::number(currentPage) + "/" + QString::number(totalPage));
}

void UserList::showUserList(QList<UInfo> &userInfoList) {
    clearUserList();
    currentUserInfoList = userInfoList;

    for(int i = 0; i < userInfoList.size(); i++) {
        ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);

        QTableWidgetItem *itm;

        //userId
        itm = new QTableWidgetItem;
        itm->setText(userInfoList.at(i).userId);
        ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 0, itm);

        //username
        itm = new QTableWidgetItem;
        itm->setText(userInfoList.at(i).username);
        ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 1, itm);

        //picPath
        QPixmap pic = QPixmap(userInfoList.at(i).picPath);//添加图片
//        pic = pic.scaled(60, 80); //设置图片的大小
        QLabel *picLabel = new QLabel();//定义一个QLabel类
        picLabel->setScaledContents(true);//设置图片适应label
//        picLabel->setMaximumSize(60, 60); //设置的大小，就是单元格的大小
        picLabel->setPixmap(pic);
        ui->tableWidget->setCellWidget(ui->tableWidget->rowCount() - 1, 2, picLabel);

        //rfidCardId
        itm = new QTableWidgetItem;
        itm->setText(userInfoList.at(i).rfidCardNo);
        ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 3, itm);

        //createTime
        itm = new QTableWidgetItem;
        itm->setText(userInfoList.at(i).createTime);
        ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 4, itm);
    }
}

void UserList::clearUserList() {
    int rowCount = ui->tableWidget->rowCount();
    for(int i = 0; i < rowCount; ++i) {
        if(ui->tableWidget->cellWidget(0, 2)->isWidgetType()) {
            ui->tableWidget->cellWidget(0, 2)->close();  // 删除图片label
        }
        ui->tableWidget->removeRow(0);
    }
}

void UserList::refreshUserList() {
    ui->searchUsernameLineEdit->setText("");
    QString strBuffer;
    strBuffer = "2000-01-01 00:00:00.000";
    ui->startTimeEdit->setDateTime(QDateTime::fromString(strBuffer, "yyyy-MM-dd hh:mm:ss.zzz"));
    ui->endTimeEdit->setDateTime(QDateTime::currentDateTime());
    getUserList(currentPage, USER_PAGE_LIST_SIZE,
                getCurrentSearchUsername(), getCurrentSearchStartTime(), getCurrentSearchEndTime());
}

void UserList::updateUser(const QModelIndex &index) {
    UInfo uInfo = currentUserInfoList[index.row()];
    qDebug() << "updateUser:" << uInfo.userId << " " << uInfo.username << " " << uInfo.picPath;
    UserRegister *userRegister = new UserRegister;
    userRegister->setWindowTitle("Update");
    userRegister->startCamera();
    userRegister->setIsUpdate();  // 告诉该页面现在是更新
    userRegister->updateSet(uInfo);
    userRegister->show();
    userRegister->setAttribute(Qt::WA_DeleteOnClose);
//    userRegister->setWindowFlags(Qt::FramelessWindowHint);//去除窗体边框
//    userRegister->setWindowModality(Qt::ApplicationModal); //阻塞除当前窗体之外的所有的窗体
}

void UserList::deleteuser(const QModelIndex &index) {
    UInfo uInfo = currentUserInfoList[index.row()];
    QMessageBox::StandardButton box;
    box = QMessageBox::question(this, "确实要删除吗?", "id:" + uInfo.userId + ",username:" + uInfo.username, QMessageBox::Yes | QMessageBox::No);
    if(box == QMessageBox::No) {
        return;
    } else {
        int result = MsgApi::getMsgApi()->userDelete(uInfo.userId);
        if(!result) {
            QMessageBox::warning(this, "删除失败", "无法发送数据");
        }
    }
}

void UserList::on_lastPageButton_clicked() {
    if(currentPage <= 1) {
        return;
    }
    currentPage--;
    getUserList(currentPage, USER_PAGE_LIST_SIZE,
                getCurrentSearchUsername(), getCurrentSearchStartTime(), getCurrentSearchEndTime());
}

void UserList::on_nextPageButton_clicked() {
    if(currentPage >= totalPage) {
        return;
    }
    currentPage++;
    getUserList(currentPage, USER_PAGE_LIST_SIZE,
                getCurrentSearchUsername(), getCurrentSearchStartTime(), getCurrentSearchEndTime());
}

void UserList::on_searchButtom_clicked() {
    getUserList(currentPage, USER_PAGE_LIST_SIZE,
                getCurrentSearchUsername(), getCurrentSearchStartTime(), getCurrentSearchEndTime());
}

void UserList::on_tableWidget_doubleClicked(const QModelIndex &index) {
    QMessageBox msgBox;
    QPushButton *updateButton = msgBox.addButton("修改", QMessageBox::ActionRole);
    QPushButton *deleteButton = msgBox.addButton("删除", QMessageBox::ActionRole);
    QPushButton *closeButton = msgBox.addButton("关闭", QMessageBox::ActionRole);

    msgBox.exec();  // 阻塞等待用户选择

    if (msgBox.clickedButton() == (QAbstractButton*)updateButton) {
        updateUser(index);
    } else if (msgBox.clickedButton() == (QAbstractButton*)deleteButton) {
        deleteuser(index);
    } else if (msgBox.clickedButton() == (QAbstractButton*)closeButton) {
        return;
    }
}

void UserList::on_refreshButton_clicked() {
    refreshUserList();
}
